package self.hoy.demo.grainmall.member.service.impl;

import org.apache.commons.lang.StringUtils;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import self.hoy.demo.common.to.auth.WeiboUser;
import self.hoy.demo.common.utils.PageUtils;
import self.hoy.demo.common.utils.Query;

import self.hoy.demo.grainmall.member.entity.MemberLevel;
import self.hoy.demo.grainmall.member.exception.PhoneExistException;
import self.hoy.demo.grainmall.member.exception.UserNameExistException;
import self.hoy.demo.grainmall.member.mapper.MemberLevelMapper;
import self.hoy.demo.grainmall.member.mapper.MemberMapper;
import self.hoy.demo.grainmall.member.entity.Member;
import self.hoy.demo.grainmall.member.service.MemberService;
import self.hoy.demo.grainmall.member.vo.MemberLoginVo;
import self.hoy.demo.grainmall.member.vo.MemberRegisterVo;

import javax.annotation.Resource;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberMapper, Member> implements MemberService {

    @Resource
    private MemberLevelMapper levelMapper;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<Member> page = this.page(
                new Query<Member>().getPage(params),
                new QueryWrapper<Member>()
        );

        return new PageUtils(page);
    }

    @Override
    public boolean isEmailUnique(String email) {
        Integer count = baseMapper.selectCount(new QueryWrapper<Member>().eq("email", email));
        return count == null || count == 0;
    }

    @Override
    public boolean isPhoneNumberUnique(String phoneNumber) {
        Integer count = baseMapper.selectCount(new QueryWrapper<Member>().eq("mobile", phoneNumber));
        return count == null || count == 0;
    }

    @Override
    public boolean isUserNameUnique(String userName) {
        Integer count = baseMapper.selectCount(new QueryWrapper<Member>().eq("username", userName));
        return count == null || count == 0;
    }

    @Override
    public void register(MemberRegisterVo vo) {
        if (!isPhoneNumberUnique(vo.getPhone())) {
            throw new PhoneExistException();
        }
        if (!isUserNameUnique(vo.getUserName())) {
            throw new UserNameExistException();
        }
        Member entity = new Member();
        entity = fillLevel(entity);
        entity.setUsername(vo.getUserName());
        entity.setNickname(vo.getUserName());
        entity.setMobile(vo.getPhone());

        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        entity.setPassword(passwordEncoder.encode(vo.getPassword()));

        baseMapper.insert(entity);
    }

    private Member fillLevel(Member entity) {
        MemberLevel level = levelMapper.getDefaultLevel();
        if (level != null) {
            entity.setLevelId(level.getId());//默认等级
        }
        entity.setCreateTime(new Date());
        return entity;
    }

    @Override
    public Member login(MemberLoginVo vo) {
        Member m = baseMapper.selectOne(
                new QueryWrapper<Member>()
                        .eq("username", vo.getAccount())
                        .or()
                        .eq("mobile", vo.getAccount())
                        .or()
                        .eq("email", vo.getAccount()));
        if (m == null) {
            return null;//登录失败
        } else {
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            boolean matches = passwordEncoder.matches(vo.getPassword(), m.getPassword());
            if (matches) {
                return m;
            } else {//登录失败
                return null;
            }
        }
    }

    @Override
    public Member login(WeiboUser vo) {
        Member member = baseMapper.selectOne(new QueryWrapper<Member>().eq("social_user_id", vo.getUid()));
        if (member == null) {
            member = new Member();
            boolean isNameUnique = StringUtils.isNotEmpty(vo.getName()) && isUserNameUnique(vo.getName());
            if (isNameUnique) {
                member.setUsername(vo.getName());
            }
            member.setExpires(vo.getExpires_in());
            member.setAccessToken(vo.getAccess_token());
            member = fillLevel(member);
            member.setNickname(vo.getName());
            member.setHeader(vo.getHeader());
            member.setGender(vo.getGender());
            member.setSocialUserId(vo.getUid());
            baseMapper.insert(member);
        } else {
            member.setExpires(vo.getExpires_in());
            member.setAccessToken(vo.getAccess_token());
            Member update = new Member();
            update.setExpires(vo.getExpires_in());
            update.setAccessToken(vo.getAccess_token());
            update.setId(member.getId());
            baseMapper.updateById(update);
        }
            //TODO 其它字段
        return member;
    }
}